<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2019/12/25
 * Time: 9:53
 */

namespace App\Services;

use Illuminate\Support\Facades\Redis;

class SwooleService
{
    private static $avatar = [
        'http://tp4.sinaimg.cn/2145291155/180/5601307179/1',
        'http://b-ssl.duitang.com/uploads/item/201704/10/20170410073535_HXVfJ.thumb.700_0.jpeg',
        'http://b-ssl.duitang.com/uploads/item/201306/27/20130627163146_eMjUf.thumb.700_0.jpeg',
        'http://files.jb51.net/scimg/web/20101008/b_1264402070027.jpg',
        'http://pic1.zhimg.com/50/v2-bf96fb79c5290318bfb4b3f70c8f88e4_hd.jpg'
    ];

    private static $role_image = [
        'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=390715617,509931490&fm=15&gp=0.jpg',
        'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3807637133,2074006413&fm=15&gp=0.jpg',
        'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3227164496,46912317&fm=15&gp=0.jpg',
        'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3867368274,1827759143&fm=15&gp=0.jpg',
    ];

    /**
     * 初始化数据
     */
    public static function store()
    {
        //配置用户组
        $friend = [
            [
                'groupname' => '陌生人',
                'avatar'    => self::$avatar[0],
                'id'        => 0,
                'list'      => []
            ]
        ];
        app('db')->table('admin_users')
            ->leftJoin('admin_role_users', 'admin_role_users.user_id', 'admin_users.id')
            ->select('admin_users.id', 'admin_users.name', 'admin_users.avatar', 'admin_users.sign')
            ->whereNull('admin_role_users.role_id')->get()->each(function ($user) use (&$friend) {
                if ($user->avatar) {
                    $arr['avatar'] = \App\Traits\ImagePath::setPath($user->avatar);
                } else {
                    $arr['avatar'] = self::$avatar[$user->id % (count(self::$avatar))];
                }
                $arr['username']              = $user->name;
                $arr['id']                    = $user->id;
                $arr['sign']                  = $user->sign;
                $friend[0]['list'][$user->id] = $arr;
            });
        //加载所有角色组
        app('db')->table('admin_roles')->select('id', 'name', 'avatar')->get()->each(function ($role) use (&$friend) {
            if ($role->avatar) {
                $role->avatar = \App\Traits\ImagePath::setPath($role->avatar);
            } else {
                $role->avatar = self::$role_image[$role->id % (count(self::$role_image))];
            }
            //写入用户组
            $friend[$role->id] = [
                'groupname' => $role->name,
                'avatar'    => $role->avatar,
                'id'        => $role->id,
                'list'      => []
            ];
            //查询出该角色下面的用户
            app('db')->table('admin_users')
                ->leftJoin('admin_role_users', 'admin_role_users.user_id', 'admin_users.id')
                ->select('admin_users.id', 'admin_users.name', 'admin_users.avatar', 'admin_users.sign')->where('admin_role_users.role_id', $role->id)->get()->each(function ($user) use ($role, &$friend) {
                    if ($user->avatar) {
                        $arr['avatar'] = \App\Traits\ImagePath::setPath($user->avatar);
                    } else {
                        $arr['avatar'] = self::$avatar[$user->id % (count(self::$avatar))];
                    }
                    $arr['username']                      = $user->name;
                    $arr['id']                            = $user->id;
                    $arr['sign']                          = $user->sign;
                    $friend[$role->id]['list'][$user->id] = $arr;
                });

        });
        Redis::set('admin_role_users', json_encode(array_values($friend), true));
    }

    /**
     * 上线
     *
     * @param $id
     * @param $bind_ids
     * @return array
     */
    public static function online($id, $bind_ids)
    {
        //判断用户是否在缓存里
        $friend = Redis::get('admin_role_users');
        $friend = json_decode($friend, true);
        //查询出当前用户
        $user = app('db')->table('admin_users')->select('id', 'name', 'avatar', 'sign')->where('id', $id)->first();
        if ($user->avatar) {
            $arr['avatar'] = \App\Traits\ImagePath::setPath($user->avatar);
        } else {
            $arr['avatar'] = self::$avatar[$user->id % (count(self::$avatar))];
        }
        $arr['username'] = $user->name;
        $arr['id']       = $user->id;
        $arr['sign']     = $user->sign;
        $arr['status']   = 'online';
        $role_ids        = app('db')->table('admin_role_users')->where('user_id', $id)->pluck('role_id')->toArray();
        if (empty($role_ids)) {
            $role_ids = [0];
        }
        $group      = [];
        $use_friend = $friend;
        foreach ($friend as $key => &$item) {
            if (in_array(1, $role_ids) or in_array($key, $role_ids)) {
                $group[] = [
                    'groupname' => $item['groupname'],
                    'id'        => $item['id'],
                    'avatar'    => $item['avatar']
                ];
            }
            foreach ($item['list'] as &$val) {
                if (in_array($val['id'], $bind_ids)) {
                    $val['status'] = 'online';
                } else {
                    $val['status'] = 'offline';
                }
            }
            if (in_array($key, $role_ids)) {
                //同步一下数据
                $item['list'][$id] = $arr;
            } else {
                if (isset($item['list'][$id])) {
                    unset($item['list'][$id]);
                }
            }
            $use_friend[$key]['list'] = array_values($item['list']);
        }
        Redis::set('admin_role_users', json_encode(array_values($friend), true));
        //设置主面板信息
        $result = [
            'mine'   => $arr,
            'friend' => $use_friend,
            'group'  => $group,
        ];
        return $result;
    }

    /**
     * 下线
     * @param $id
     */
    public static function offline($id)
    {
        //判断用户是否在缓存里
        $friend = Redis::get('admin_role_users');
        $friend = json_decode($friend, true);
        foreach ($friend as $key => &$item) {
            if (isset($item['list'][$id])) {
                $item['list'][$id]['status'] = 'offline';
            }
        }
        Redis::set('admin_role_users', json_encode(array_values($friend), true));
    }

    /**
     * 修改个人信息
     *
     * @param $data
     */
    public static function updateUser($data){
        //判断用户是否在缓存里
        $friend = Redis::get('admin_role_users');
        $friend = json_decode($friend, true);
        foreach ($friend as $key => &$item) {
            if (isset($item['list'][$data['id']])) {
                foreach ($data as $key=>$val){
                    $item['list'][$data['id']][$key] = $val;
                }
            }
        }
        Redis::set('admin_role_users', json_encode(array_values($friend), true));
    }
}